/**
 * 
 */
package com.dycn.posdashboard.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @author gongqiyi
 *
 */
public class HttpClientUtils {
	private static Logger log = Logger.getLogger(HttpClientUtils.class);  
    
    @SuppressWarnings("deprecation")
	public static String post(String url, Map<String, String> params) {  
    	CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        String body = null;  
          
        log.info("create httppost:" + url);  
        HttpPost post = postForm(url, params);  
          
        body = invoke(httpclient, post);  
          
        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
      
    @SuppressWarnings("deprecation")
	public static String get(String url) {  
    	CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
        String body = null;  
          
        log.info("create httppost:" + url);  
        HttpGet get = new HttpGet(url);  
        body = invoke(httpclient, get);  

        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
          
      
    private static String invoke(CloseableHttpClient httpclient,  
            HttpUriRequest httpost) {  
          
        HttpResponse response = sendRequest(httpclient, httpost);  
        String body = paseResponse(response);  
          
        return body;  
    }  
  
    private static String paseResponse(HttpResponse response) {  
        log.info("get response from http server..");  
        HttpEntity entity = response.getEntity();  
          
        log.info("response status: " + response.getStatusLine());  
        String charset = ContentType.getOrDefault(entity).getMimeType();
        log.info(charset);  
          
        String body = null;  
        try {  
            body = EntityUtils.toString(entity);  
            log.info(body);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        return body;  
    }  
  
    private static HttpResponse sendRequest(CloseableHttpClient httpclient,  
            HttpUriRequest httpost) {  
        log.info("execute post...");  
        HttpResponse response = null;  
          
        try {  
            response = httpclient.execute(httpost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return response;  
    }  
  
    private static HttpPost postForm(String url, Map<String, String> params){  
          
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
          
        Set<String> keySet = params.keySet();  
        for(String key : keySet) {  
            nvps.add(new BasicNameValuePair(key, params.get(key)));  
        }  
          
        log.info("set utf-8 form entity to httppost");  
		httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  
          
        return httpost;  
    }  
    
    public static String postBody(String url, Map<String,Object> params, String encoding) throws Exception{
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
    	String responseContent="";
        try {  
    	  CookieStore cookieStore = new BasicCookieStore();
          // Create local HTTP context
          HttpContext localContext = new BasicHttpContext();
          // Bind custom cookie store to the local context
          localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
              
            HttpPost httpost = new HttpPost(url);  

            String jsonFormatedRequestDatas=JSONObject.fromObject(params).toString();
            log.info("jsonFormatedRequestDatas:"+jsonFormatedRequestDatas);
            HttpEntity requestEntity = new ByteArrayEntity(jsonFormatedRequestDatas.getBytes("UTF-8"));
            httpost.setEntity(requestEntity);  
            
            HttpResponse response = httpclient.execute(httpost);  
            HttpEntity entity = response.getEntity();  
  
            log.info("respons : " + response.getStatusLine() +" "
                    + entity.getContent());  
//            dump(entity, encoding);  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    entity.getContent(), encoding)); 
            StringBuffer resultBuffer=new StringBuffer();
            String s="";
            while ((s = br.readLine()) != null) {
               // System.out.println(s);
            	resultBuffer.append(s);
            }

            responseContent=resultBuffer.toString();
            log.info("url responseContent:"+responseContent);
  
        } finally {  
            // 关闭请求  
            httpclient.getConnectionManager().shutdown();  
        } 
        
        return responseContent;
        
    }
    
    /**
     * 保证请求参数的顺序
     * @param url
     * @param params
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String postJsonBody(String url, LinkedHashMap<String,Object> params, String encoding) throws Exception{
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
    	String responseContent="";
        try {  
    	  CookieStore cookieStore = new BasicCookieStore();
          // Create local HTTP context
          HttpContext localContext = new BasicHttpContext();
          // Bind custom cookie store to the local context
          localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
              
            HttpPost httpost = new HttpPost(url);  
            log.info("url:"+url);
            String jsonFormatedRequestDatas=JSONObject.fromObject(params).toString();
            log.info("jsonFormatedRequestDatas:"+jsonFormatedRequestDatas);
    		Iterator<String> iteratorStr=params.keySet().iterator();
    		
    		StringBuffer reqestJsonBuffer=new StringBuffer();
    		reqestJsonBuffer.append("");
    		while(iteratorStr.hasNext()){
    			String key=iteratorStr.next();
    			
    			reqestJsonBuffer.append(","+"\""+key+"\":\""+params.get(key)+"\"");
    		}
    		reqestJsonBuffer=new StringBuffer("{"+reqestJsonBuffer.substring(1));
    		reqestJsonBuffer.append("}");
    		log.info("jsonFormatedRequestDatas:"+reqestJsonBuffer.toString());
    		jsonFormatedRequestDatas=reqestJsonBuffer.toString();
    		
            HttpEntity requestEntity = new ByteArrayEntity(jsonFormatedRequestDatas.getBytes("UTF-8"));
            httpost.setEntity(requestEntity);  
            httpost.addHeader("content-type", "application/json");  
            //StringEntity params =new StringEntity(jsonString,"UTF-8");  
            
            HttpResponse response = httpclient.execute(httpost);  
            HttpEntity entity = response.getEntity();  
  
            log.info("respons : " + response.getStatusLine() +" "
                    + entity.getContent());  
//            dump(entity, encoding);  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    entity.getContent(), encoding)); 
            StringBuffer resultBuffer=new StringBuffer();
            String s="";
            while ((s = br.readLine()) != null) {
               // System.out.println(s);
            	resultBuffer.append(s);
            }

            responseContent=resultBuffer.toString();
            log.info("url responseContent:"+responseContent);
  
        } finally {  
            // 关闭请求  
            httpclient.getConnectionManager().shutdown();  
        } 
        
        return responseContent;
        
    }
    public static String postUrlWithParams(String url, Map params, String encoding)  
            throws Exception {  
    	CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
    	String responseContent="";
        try {  
    	  CookieStore cookieStore = new BasicCookieStore();
          // Create local HTTP context
          HttpContext localContext = new BasicHttpContext();
          // Bind custom cookie store to the local context
          localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
              
            HttpPost httpost = new HttpPost(url);  
            // 添加参数  
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
            if (params != null && params.keySet().size() > 0) {  
                Iterator iterator = params.entrySet().iterator();  
                while (iterator.hasNext()) {  
                    Map.Entry entry = (Entry) iterator.next();  
                    nvps.add(new BasicNameValuePair((String) entry.getKey(),  
                            (String) entry.getValue()));  
                }  
            }  
  
            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  
  
            HttpResponse response = httpclient.execute(httpost);  
            HttpEntity entity = response.getEntity();  
  
            System.out.println("Login form get: " + response.getStatusLine()  
                    + entity.getContent());  
//            dump(entity, encoding);  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    entity.getContent(), encoding)); 
            StringBuffer resultBuffer=new StringBuffer();
            String s="";
            while ((s = br.readLine()) != null) {
               // System.out.println(s);
            	resultBuffer.append(s);
            }

            responseContent=resultBuffer.toString();
            log.info("url responseContent:"+responseContent);
//            System.out.println("Post logon cookies:");  
//            List<Cookie> cookies = cookieStore.getCookies();
//            if (cookies.isEmpty()) {  
//                System.out.println("None");  
//            } else {  
//                for (int i = 0; i < cookies.size(); i++) {  
//                    System.out.println("- " + cookies.get(i).toString());  
//                }  
//            }  
  
        } finally {  
            // 关闭请求  
            httpclient.getConnectionManager().shutdown();  
        } 
        
        return responseContent;
    } 
    
    
    private static void dump(HttpEntity entity, String encoding)  
            throws IOException {  
        BufferedReader br = new BufferedReader(new InputStreamReader(  
                entity.getContent(), encoding));  
        System.out.println(br.readLine());  
    }
}
